# -*- coding:utf-8 -*-
# author：Anson
# @Time    : 2019/10/28 15:12
# @File    : serializers.py
from __future__ import unicode_literals

from datetime import datetime

from rest_framework import viewsets
from rest_framework.decorators import action
from common.api import APIResponse
from django.db import transaction
from xpinyin import Pinyin
from django.db import transaction
from django.contrib.auth.models import Group

from .serializers import *
from .models import *



class AttendanceViewSet(viewsets.GenericViewSet):
    serializer_class = AttendanceSerializer

    @action(methods=['post'], detail=False)
    def attendance(self, request, *args, **kwargs):
        """
        考勤api http://127.0.0.1:8000/api/v1/accounts/attendance/
        """
        sz = AttendanceSerializer(data=request.data)
        if not sz.is_valid():
            return APIResponse(errors=sz.errors)
        attendance_group = sz.validated_data.get('attendance_group')
        attendance_date = sz.validated_data.get('attendance_date')
        in_date = sz.validated_data.get('in_date')
        back_date = sz.validated_data.get('back_date')
        print(attendance_date, in_date, back_date)
        # 字符串的格式"2019-10-28 06:26:00"
        try:
            attendance_date = datetime.strptime(attendance_date, "%Y-%m-%d")
            in_date = datetime.strptime(in_date, "%H:%M")
            back_date = datetime.strptime(back_date, "%H:%M")
        except:
            return APIResponse(errors={'date_invalid': ['时间格式错误！']})
        try:
            people = ProjectPeople.objects.get(attendance_group=attendance_group)
        except ProjectPeople.DoesNotExist:
            return APIResponse(errors={'name_invalid': ['项目组成员不存在！']})

        Attendance.objects.create(people=people,
                                  attendance_date=attendance_date,
                                  in_date=in_date,
                                  back_date=back_date)
        return APIResponse()

    @action(methods=['post'], detail=False)
    def create_user(self, request, *args, **kwargs):
        """
        考勤api http://127.0.0.1:8000/api/v1/accounts/create_user/
        """
        sz = UserSerializer(data=request.data)
        if not sz.is_valid():
            return APIResponse(errors=sz.errors)
        name = sz.validated_data.get('name')
        username = sz.validated_data.get('username')
        email = sz.validated_data.get('email')
        num = sz.validated_data.get('num')
        user = User.objects.create(username=username,
                                   email=email,
                                   password='pbkdf2_sha256$150000$lAdJrWNAbkVC$jyI0JfZutg2PLdUCm/tXcbehGxYUKbS5rsAymO7E5+g=',
                                   is_password_set=True,
                                   is_staff=True,
                                   is_superuser=False)
        user.save()
        project = ProjectGroup.objects.get(id=num)
        ProjectPeople.objects.create(project=project,
                                     name=name,
                                     user=user,
                                     attendance_group=username)
        return APIResponse()

class ModifePositionViewSet(viewsets.GenericViewSet):
    serializer_class = None

    @action(methods=['get'], detail=False)
    def modife_position(self, request, *args, **kwargs):
        """
        修改考勤顺序 http://127.0.0.1:8000/api/v1/position/modife_position/?name={}&position={}
        """
        name = request.GET.get('name')
        position = request.GET.get('position')
        print(name, position)
        with transaction.atomic():
            try:
                project_people = ProjectPeople.objects.select_for_update().get(name=name)
            except ProjectPeople.DoesNotExist:
                return APIResponse(errors={'name_invalid': ['项目组成员不存在！']})
            project_people.position = position
            project_people.save(update_fields=[
                'position'])
        return APIResponse()


class RegisterednViewSet(viewsets.GenericViewSet):
    serializer_class = RegisteredSerializer

    @action(methods=['post'], detail=False)
    def register(self, request, *args, **kwargs):
        sz = RegisteredSerializer(data=request.data)
        if not sz.is_valid():
            pass
            # return APIResponse(errors=sz.errors)
        name = sz.validated_data.get('name')
        name = name.strip()
        username = sz.validated_data.get('username')
        username = username.strip()
        email = sz.validated_data.get('email')
        password = sz.validated_data.get('password')
        team_type = sz.validated_data.get('team_type')
        project_name = sz.validated_data.get('project_name')
        if User.objects.filter(username=username).exists():
            return APIResponse(errors={'username_invalid': ['用户名已存在！']})

        if User.objects.filter(email=email).exists():
            return APIResponse(errors={'email_invalid': ['邮箱已存在！']})

        if len(password) < 8 or len(password) > 18:
            return APIResponse(errors={'password_invalid': ['密码格式错误，必须为8-16位字母或数字！']})

        try:
            project_id = ProjectGroup.objects.get(project_name=project_name)
        except ProjectGroup.DoesNotExist:
            return APIResponse(errors={'project_name_invalid': ['项目组不存在！']})
        p = Pinyin()
        attendance_group = p.get_pinyin(name, '')
        if team_type not in ('数据小组', '安全小组'):
            return APIResponse(errors={'team_type_invalid': ['所属小组必须为"数据小组"或"安全小组"！']})
        
        if team_type == '数据小组':
            team = 1
        else:
            team = 0 
        with transaction.atomic():
            user = User.objects.create(username=username, email=email, is_staff=True)
            if password:
                user.set_password(password)
                user.is_password_set = True
            else:
                user.is_password_set = False
            group = Group.objects.get(id=1)
            user.groups.add(group)
            user.save(update_fields=['password', 'is_password_set'])

            ProjectPeople.objects.create(project=project_id, name=name, user=user, 
                                        attendance_group=attendance_group, team_type=team)
        return APIResponse()
